package com.demo.persistencia.generica.util;

import org.apache.log4j.EnhancedPatternLayout;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.jdbc.JDBCAppender;

public class Log4jRedefinido extends JDBCAppender {

	private static Logger log = Logger.getLogger(Log4jRedefinido.class);
	private int _canMaxDias;
	private int cantMaxRegistrosBK;
	
	public int get_canMaxDias() {
		return _canMaxDias;
	}

	public void set_canMaxDias(int _canMaxDias) {
		log.info("_canMaxDias : " +_canMaxDias);
		this._canMaxDias = _canMaxDias;
	}

	public Log4jRedefinido() {
		super();
	}

	public void setCantMaxRows(int cantMaxRows) {
		log.info("setCantMaxRows : " +cantMaxRows);
		this.cantMaxRegistrosBK = cantMaxRows;
	}

	public int getCantMaxRegistrosBK() {
		return cantMaxRegistrosBK;
	}

	@Override
	 public void setSql(String s) {
	    super.sqlStatement = s;
	    log.info("sqlStatement : " +sqlStatement);
	    if (getLayout() == null) {
	      setLayout(new PatternLayout(this.ejecutar(s)));
	    }
	    else
	      ((EnhancedPatternLayout)getLayout()).setConversionPattern(this.ejecutar(s));
	  }

	public String ejecutar(String sentencia){
		String sqlEjecutar="";
		String sqlMaxDias = " Delete from DEMO01.LOG4JDATA where (SYSTIMESTAMP - Fecha)<numtodsinterval("+_canMaxDias+",'day');";
		String sqlMaxRows = "DECLARE l_exists INTEGER; "+
			    " BEGIN"+
                " SELECT COUNT(*) INTO l_exists FROM DEMO01.LOG4JDATA;"+
                " IF l_exists >= "+cantMaxRegistrosBK+" THEN "+
                " DELETE FROM DEMO01.LOG4JDATA; "+
                " ELSE "+ sentencia+ ";" +
                " END IF; "+
                " END;  ";
		
		if(cantMaxRegistrosBK!=0){
			sqlEjecutar  = sqlMaxRows;
		}
		if(_canMaxDias!=0){
			sqlEjecutar += sqlMaxDias;
		}
		log.info("ejecutar sql : ::: " +sqlEjecutar);
		return sqlMaxRows;
	}

	

}
